/**
 * Created by lihao on 2017/3/20.
 */
var ApiService = require('../../module/ApiService');
var Promise = require('bluebird');

module.exports = function () {
	var componentBase;
	avalon.component('ms-list', {
		template: '<div class="list-view"><slot /></div>',
		defaults: {
			list: [],
			listOrg: [],
			listParams: {},
			filterParams: {},
			filterLock: false,
			config: {},
			formPageNumber: '',
			pageTotal: 0,
			totalCount: 0,
			autoLoad: true,
			prevData: {},
			page: 0,
			initFn: function (conf) {
				var _this = this;
				_this.listParams = conf.params;
				_this.filterParams = conf.filterParams;
				return Promise.resolve(_this.listParams);
			},
			doSetParams: function (params) {
				var _this = this;
				var Index = layer.load(1, {shade: [0.3, '#000'], scrollbar: false});
				return _this.setListParams(params)
					.then(_this.refresh)
					.then(_this.formatData)
					.then(_this.cleanData)
					.then(function (data) {
						_this.list = data.list;
						if (!_this.filterLock) _this.listOrg = data.list.$model;
						$('.list-view').trigger('refreshSuccess');
						layer.close(Index);
						return null
					}).catch(function (error) {
						$('.list-view').trigger('reloadError');
						layer.close(Index);
					});
			},
			doFormParams: function (params) {
				var _this = this;
				var Index = layer.load(1, {shade: [0.3, '#000'], scrollbar: false});
				_this.setListParams(params)
					.then(_this.refresh)
					.then(_this.formatData)
					.then(_this.cleanData)
					.then(function (data) {
						_this.list = data.list;
						if (!_this.filterLock) _this.listOrg = data.list.$model;
						$('.list-view').trigger('refreshSuccess');
						layer.close(Index);
						return null
					}).catch(function (error) {
					$('.list-view').trigger('reloadError');
					layer.close(Index);
				});
				return false;
			},
			setFilterLock: function (status) {
				this.filterLock = status;
			},
			doFilter: function (params) {
				var _this = this;
				_this.filterParams = $.extend(_this.filterParams, params);
				if (!_.isEmpty(_this.filterParams)) {
					this.list = _.filter(_this.listOrg, function (item) {
						var arr = _.omit(_this.filterParams, function (item, key) {
							return item == '';
						});
						var status = _.map(arr, function (filterValue, filterKey) {
							if (_.has(item, filterKey)) {
								if (_.isArray(item[filterKey])) {
									return _.indexOf(item[filterKey].$model, filterValue) >= 0;
								} else {
									return item[filterKey] == filterValue;
								}
							} else {
								return false;
							}
						});
						var count = _.countBy(status, function (n) {
							return n;
						});
						return !_.has(count, 'false');
					});
				} else {
					this.list = this.listOrg.$model;
				}
			},
			doClearParams: function (arr) {
				var _this = this;
				var Index = layer.load(1, {shade: [0.3, '#000'], scrollbar: false});
				_this.clearParams(arr)
					.then(_this.refresh)
					.then(_this.formatData)
					.then(_this.cleanData)
					.then(function (data) {
						_this.list = data.list;
						if (!_this.filterLock) _this.listOrg = data.list.$model;
						$('.list-view').trigger('refreshSuccess');
						layer.close(Index);
						return null
					}).catch(function (error) {
					$('.list-view').trigger('reloadError');
					layer.close(Index);
				});
			},
			setParams: function (type, value) {
				var _this = this;
				_this.listParams = _.set(_this.listParams, type, value);
				return Promise.resolve(true);
			},
			getParams: function (type) {
				var _this = this;
				return _.result(_this.listParams, type);
			},
			setListParams: function (data) {
				var _this = this;
				_this.listParams = $.extend(_this.listParams, data);
				return Promise.resolve(_this.listParams);
			},
			getListParams: function () {
				var _this = this;
				return _this.listParams;
			},
			clearParams: function (arr) {
				var _this = this;
				if (_.isEmpty(arr)) {
					_this.listParams = _this.config.params.$model;
					_this.pageTotal = 0;
					_this.page = 1;
				} else {
					_.map(arr, function (item) {
						_.set(_this.listParams, item, '');
					});
					_.set(_this.listParams, 'pageNumber', 1);

					_this.pageTotal = 0;
					_this.page = 1;
				}
				return Promise.resolve(true);
			},
			refresh: function () {
				var _this = this;
				return ApiService.postApi(_this.config.post, _this.listParams)
					.then(ApiService.error)
			},
			formatData: function (data) {
				var _this = this;
				_this.pageTotal = data.data.totalPages;
				_this.totalCount = data.data.total;
				_this.page = _this.listParams.pageNumber;
				if (!_.isEmpty(_this.config.listName)) {
					_.set(data, 'list', _.get(data, _this.config.listName));
				}
				_.map(data.list, function (item) {
					_.set(item, 'isChecked', false);
				});

				var noneSearch = $('body').find('.noneSearch');

				if (data.list.length <= 0) {
					noneSearch.find('span').text(ApiService.getUrlParams('keyWords'));
					noneSearch.show();
				} else {
					noneSearch.hide();
				}
				return Promise.resolve(data);

			},
			cleanData: function (data) {
				data.list = _.map(data.list, function (item) {
					item = _.transform(item, function (r, value, key) {
						if (value == null || value == undefined || value == 'null' || value == 'undefined') {
							r[key] = '';
						} else {
							r[key] = value;
						}
					}, {});
					return item;
				});
				return Promise.resolve(data);
			},
			pageStatus: function () {
				var _this = this;
				var startPage = 1;
				var endPage = _this.pageTotal + 1;
				var pageNumberCount;
				pageNumberCount = parseInt(_this.listParams.pageNum);
				if (_this.pageTotal > 10 && ((pageNumberCount + 4 > 10) && (pageNumberCount + 5 <= _this.pageTotal))) {
					startPage = pageNumberCount - 5;
					endPage = pageNumberCount + 5;
				} else if (_this.pageTotal > 10 && ((pageNumberCount + 4 > 10) && (pageNumberCount + 5 > _this.pageTotal))) {
					startPage = _this.pageTotal - 9;
				} else if (_this.pageTotal > 10) {
					endPage = 11;
				}
				return {
					pageTotal: _this.pageTotal,
					totalPage: _this.totalCount,
					nextPage: _this.page + 1 > _this.pageTotal ? 0 : _this.page + 1,
					prevPage: _this.page - 1 == 0 ? 1 : _this.page - 1,
					pageArr: _this.pageTotal > 0 ? _.range(startPage, endPage) : []
				}
			},
			listPrevPage: function () {
				var _this = this;
				var apiName = 'pageNumber';
				if (_this.pageStatus().prevPage) {
					var Index = layer.load(1, {shade: [0.3, '#000'], scrollbar: false});
					return _this.setParams(apiName, _this.pageStatus().prevPage)
						.then(_this.refresh)
						.then(_this.formatData)
						.then(_this.cleanData)
						.then(function (data) {
							_this.list = data.list;
							if (!_this.filterLock) _this.listOrg = data.list.$model;
							layer.close(Index);
							return null
						}).catch(function (error) {
							$('.list-view').trigger('reloadError');
							layer.close(Index);
						});
				}
			},
			listNextPage: function () {
				var _this = this;
				var apiName = 'pageNumber';
				if (_this.pageStatus().nextPage) {
					var Index = layer.load(1, {shade: [0.3, '#000'], scrollbar: false});
					return _this.setParams(apiName, _this.pageStatus().nextPage)
						.then(_this.refresh)
						.then(_this.formatData)
						.then(_this.cleanData)
						.then(function (data) {
							_this.list = data.list;
							if (!_this.filterLock) _this.listOrg = data.list.$model;
							layer.close(Index);
							return null
						}).catch(function (error) {
							$('.list-view').trigger('reloadError');
							layer.close(Index);
						});
				}
			},
			toPage: function (page) {
				var _this = this;
				var Index = layer.load(1, {shade: [0.3, '#000'], scrollbar: false});
				var apiName = 'pageNumber';
				return _this.setParams(apiName, page)
					.then(_this.refresh)
					.then(_this.formatData)
					.then(_this.cleanData)
					.then(function (data) {
						_this.list = data.list;
						if (!_this.filterLock) _this.listOrg = data.list.$model;
						layer.close(Index);
						return null;
					}).catch(function (error) {
						$('.list-view').trigger('reloadError');
						layer.close(Index);
					});
			},
			goToPage: function (e) {
				var _this = this;
				var apiName = 'pageNumber';
				var orgVal = $(e.target).parent().find('input[name=pageNumber]').val();
				var pageNumber = 1;
				if (/\d+/.test(orgVal)) {
					pageNumber = parseInt(orgVal)
				}

				if (pageNumber <= 0) pageNumber = 1;
				// console.log(_this.pageStatus().pageTotal, typeof _this.pageStatus().pageTotal)
				// console.log(pageNumber, typeof pageNumber)
				if (pageNumber > _this.pageStatus().pageTotal) pageNumber = _this.pageStatus().pageTotal;
				$(e.target).parent().find('input[name=pageNumber]').val(pageNumber);
				var Index = layer.load(1, {shade: [0.3, '#000'], scrollbar: false});
				return _this.setParams(apiName, pageNumber)
					.then(_this.refresh)
					.then(_this.formatData)
					.then(_this.cleanData)
					.then(function (data) {
						_this.list = data.list;
						if (!_this.filterLock) _this.listOrg = data.list.$model;
						layer.close(Index);
						return null;
					}).catch(function (error) {
						$('.list-view').trigger('reloadError');
						layer.close(Index);
					});
			},
			groupByAttr: function (attrName) {
				return _.compact(_.keys(_.groupBy(this.listOrg, attrName)));
			},
			groupByAttrToArr: function (attrName) {
				var temp = _.compact(_.keys(_.groupBy(this.listOrg, attrName)));
				return _.union(_.flattenDeep(_.map(temp, function (item) {
					if (item == 'undefined') {
						return [];
					} else {
						return item.split(',');
					}
				})));
			},
			onInit: function (e) {
				componentBase = e.vmodel;
				var _this = this;
				if (_this.autoLoad) {
					_this.initFn(_this.config.$model)
						.then(function () {
							return _this.setListParams(ApiService.getParams());
						})
						.then(_this.refresh)
						.then(_this.formatData)
						.then(_this.cleanData)
						.then(function (data) {
							_this.list = data.list;
							if (!_this.filterLock) _this.listOrg = data.list.$model;
							return null;

						}).catch(function (error) {
						$('.list-view').trigger('reloadError');
						return null;
					});
				} else if (!_.isEmpty(_this.prevData.$model)) {
					_this.initFn(_this.config.$model)
						.then(function () {
							return _this.setListParams(ApiService.getParams());
						})
						.then(function () {
							return Promise.resolve(_this.prevData.$model);
						})
						.then(_this.formatData)
						.then(_this.cleanData)
						.then(function (data) {
							_this.list = data.list;
							if (!_this.filterLock) _this.listOrg = data.list.$model;
							return null;
						}).catch(function (error) {
						$('.list-view').trigger('reloadError');
						return null;
					});

				}
				$(e.target).on('reload', function (type) {
					_this.initFn(_this.config.$model)
						.then(function () {
							return _this.setListParams(ApiService.getParams());
						})
						.then(function () {
							return Promise.resolve(_this.prevData.$model);
						})
						.then(_this.formatData)
						.then(_this.cleanData)
						.then(function (data) {
							_this.list = data.list;
							if (!_this.filterLock) _this.listOrg = data.list.$model;
							$('.list-view').trigger('reloadSuccess');
							return null;
						}).catch(function (error) {
						$('.list-view').trigger('reloadError');
						console.log(error);
						return null;
					});
				});
				$(e.target).on('refresh', function () {
					var Index = layer.load(1, {shade: [0.3, '#000'], scrollbar: false});
					_this.refresh()
						.then(_this.formatData)
						.then(_this.cleanData)
						.then(function (data) {
							_this.list = data.list;
							if (!_this.filterLock) _this.listOrg = data.list.$model;
							$('.list-view').trigger('refreshSuccess');
							layer.close(Index);
							return null
						}).catch(function (error) {
						$('.list-view').trigger('reloadError');
						layer.close(Index);
					});
				});


			},
			onReady: function () {

			},
			selectAll: function (e) {
				var _this = this;
				_.map(_this.list, function (item) {
					_.set(item, 'isChecked', $(e.target).is(':checked'));
				});
			},
			select: function (el, str, e) {
				var _this = this;
				_.map(_this.list, function (item) {
					if (item[str] == el[str]) _.set(item, 'isChecked', $(e.target).is(':checked'));
				});

			},
			getSelect: function (str) {
				var _this = this;
				if (str == undefined) {
					return _.filter(_this.list, {isChecked: true});
				} else {
					return _.map(_.filter(_this.list, {isChecked: true}), function (item) {
						return item[str]
					});
				}

			},
			allCheckStatus: function () {
				var _this = this;
				return !_.has(_.countBy(_this.list, 'isChecked'), 'false');
			}
		},
		soleSlot: 'list-content'
	});
	return {
		get: function () {
			return componentBase;
		}
	}
}();
